package com.ray.test.proxy;

import com.ray.test.actuator.result.ResultBuilder;
import com.ray.test.mock.MockConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * @author bo shen
 * @Description: 对象代理
 * @Class: Handler
 * @Package test.runner
 * @date 2019/9/29 16:16
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
public class Handler implements InvocationHandler, MethodInterceptor {

    private static final Log logger = LogFactory.getLog(Handler.class);

    private Class<?> clazz;

    public Handler(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       return  doAll(proxy,method,args);
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        return  doAll(o,method,objects);
    }

    private Object doAll(Object proxy, Method method, Object[] args) {
        //读取全局配置
        //获取返回类型
        Map<Class<?>, Object> result =  MockConfig.getResult().get();
        if (result != null && result.containsKey(method.getReturnType())) {
            return result.get(method.getReturnType());
        }
        //读取是否配置默认
        Map<String, Object> paramsMap = MockConfig.getMethodResult().get().get(clazz);
        if (paramsMap != null && paramsMap.containsKey(method.getName())) {
            return paramsMap.get(method.getName());
        }
        //读取无配置
        Type type = method.getGenericReturnType();
        return ResultBuilder.getInstance().bulider(method, type);
    }


}
